/**
 * @description seed-form-base 赛事报名基本表单
 * @author ouxh862
 * 赛事表单的填写分为固定项 和 自定义项
 * 其中固定项为 [姓名、性别、手机号、身份证号、出生日期]
 * 自定义项为 此项为后台返回数组 matchSignupFields 字段，根据 B端 的设置内容
 *
 *
 * @input addition: MatchSignupFieldsResp[] 设置自定义项
 * @input defaultValue 设置表单的默认值
 * {
 *    idNo?: ''
 *    commingName?: ''
 *    birthday?: ''
 *    linkPhone?: ''
 *    sex?: '',
 *    [key: string]?: string;
 * }
 *
 * Example
 *  html:
 *  <seed-form-base [addition]="addition" [defaultValue]="defaultValue" ></seed-form-base>
 *  ts:
 *  //@ViewChild(FormBaseComponent) formBase;
 *  this.formBase.signForm.controls 为当前赛事报名的表单控制器对象 可循环遍历出各项的值value
 *
 */

import {
  Component, OnInit, ViewEncapsulation, Input, OnDestroy, ViewChild
} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

import {ValidationService} from "@shared/service/validator/validator.service";
import {Subject} from "rxjs/Subject";
import {DynamicFormDefault, MatchSignupFieldsResp} from "@interface/index";


@Component({
  selector: 'seed-form-base',
  templateUrl: './form-base.component.html',
  styleUrls: ['./form-base.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FormBaseComponent implements OnInit, OnDestroy {
  private _defaultValue: DynamicFormDefault;
  public signForm: FormGroup;
  public hasSetDefault = false;
  public _addition: Array<any> = [];
  public baseArr = ['idNo', 'commingName', 'linkPhone', 'sex', 'birthday'];

  @Input()
  set addition(arr: MatchSignupFieldsResp[]) {
    this._addition = arr;
    if (this.addition && this.addition.length > 0) {
      this.addition.forEach(e => {
        if (e.fieldType === 1) {  // 文本框
          const control = new FormControl('', [Validators.required, Validators.maxLength(50), ValidationService.customValidator]);
          this.signForm.addControl(e.fieldText + '', control);
        } else {
          this.signForm.addControl(e.fieldText + '', new FormControl('', [Validators.required]));
        }
      });
    }
  }

  get addition() {
    return this._addition;
  }

  @Input()
  set defaultValue(val) {
    this._defaultValue = val;
    this.setFormDefault();
  }

  get defaultValue() {
    return this._defaultValue;
  }

  private ngUnsubscribe: Subject<any> = new Subject<any>();

  constructor(private formbuilder: FormBuilder) {
    this.signForm = this.formbuilder.group({
      commingName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(10), ValidationService.idNameValidator]],
      idNo: ['', [Validators.required, Validators.maxLength(30), ValidationService.certificateValidator]],
      linkPhone: ['', [Validators.required, ValidationService.accountValidator]],
      sex: ['', [Validators.required]],
      birthday: ['', [Validators.required]],
    });
    this.signForm.valueChanges.takeUntil(this.ngUnsubscribe).subscribe(res => {
      // console.log(this.signForm); //
    });
  }

  ngOnInit() {

  }

  setBaseDefault(text: string) {
    return this.defaultValue && this.defaultValue[text] ? this.defaultValue[text] : '';
  }

  setFormDefault() {
    if (this.hasSetDefault) {
      return;
    }
    setTimeout(() => {
      if (this.defaultValue) {
        for (const item in this.defaultValue) {
          if (this.baseArr.indexOf(item) > -1 && this.defaultValue[item]) {
            this.signForm.controls[item].setValue(this.defaultValue[item]);
          } else if (item === 'matchSignFieldReqs') {
            this.defaultValue.matchSignFieldReqs.forEach(each => {
              this.signForm.controls[each.fieldText].setValue(each.fieldValue);
            });
          }
        }
      }
      this.hasSetDefault = true;
    }, 500);

  }

  setCustomerDefault(text: string) {
    let temp = '';
    if (this.defaultValue && this.defaultValue.matchSignFieldReqs && this.defaultValue.matchSignFieldReqs.length > 0) {
      this.defaultValue.matchSignFieldReqs.forEach(e => {
        if (e.fieldText === text) {
          temp = e.fieldValue;
        }
      });
    }
    return temp;
  }


  itemChagne(value, name) {
    // console.log(value);
    this.signForm.controls[name].setValue(value);
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
